package com.androwit.engine.mapping.converter.str;

import java.util.Map;

import com.androwit.engine.mapping.Converter;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import flexjson.ObjectFactory;
import flexjson.transformer.Transformer;

public class JsonConverter<T> implements Converter<T, String> {
	protected JSONSerializer jsonSerializer = new JSONSerializer();
	protected JSONDeserializer<T> jsonDeserializer = new JSONDeserializer<T>();
	protected Map<String, Transformer> propertiesTransformers;

	public JsonConverter() {
	}

	public JsonConverter(Map<String, Transformer> propertiesTransformers) {
		this.propertiesTransformers = propertiesTransformers;
		// if(propertiesTransformers)
	}

	public JsonConverter(Map<String, Transformer> propertiesTransformers, String... onlyProps) {
		this(propertiesTransformers);
		jsonSerializer = jsonSerializer.include("class").include(onlyProps).exclude("*");
	}

	@Override
	public String convert(T value) throws Exception {
		if (value == null)
			return null;
		return jsonSerializer.serialize(value);
	}

	@Override
	public T fromConverted(String value) throws Exception {
		// FIXME check why creator is empty
		if (value == null || "{}".equals(value))
			return null;
		return jsonDeserializer.deserialize(value);
	}

	public JsonConverter<T> bind(Class<?> clazz, Transformer transformer) {
		jsonDeserializer.use(clazz, (ObjectFactory) transformer);
		jsonSerializer.transform(transformer, clazz);
		return this;
	}

	public JsonConverter<T> includeProperties(String... fields) {
		jsonSerializer.include(fields);
		return this;
	}

	public JsonConverter<T> skipProperties(String... fields) {
		jsonSerializer.exclude(fields);
		return this;
	}
}
